package com.example.huawei.system.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class HwUtils {
    /**
     * 小程序id
     */
    private static String clientId;
    /**
     * 小程序密钥
     */
    private static String clientSecret;

    /**
     * 获取token
     */
    public static String getAccessToken(String code) {

        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            String url = "https://oauth-login.cloud.huawei.com/oauth2/v3/token?grant_type=authorization_code" +
                    "&code=" + code +
                    "&client_id=" + clientId +
                    "&client_secret=" + clientSecret;
            HttpPost post = new HttpPost(url);
            post.setHeader("Content-Type", "application/x-www-form-urlencoded");
            CloseableHttpResponse response = httpclient.execute(post);
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            JSONObject json = JSONObject.parseObject(result);
            if (!json.containsKey("error")) {
                return json.getString("access_token");
            }
        } catch (IOException e) {
            e.printStackTrace();
//            throw new JeecgBootException("openid获取失败");
        }
        return null;
    }

    /**
     * 获取用户信息
     */
    public static JSONObject login(String accessToken) {

        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            String url = "https://account.cloud.huawei.com/rest.php?nsp_svc=GOpen.User.getInfo?access_token=" +accessToken;
            HttpPost post = new HttpPost(url);
            post.setHeader("Content-Type", "application/x-www-form-urlencoded");
            CloseableHttpResponse response = httpclient.execute(post);
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            JSONObject json = JSONObject.parseObject(result);
            if (!json.containsKey("error")) {
                return json;
            }
        } catch (IOException e) {
            e.printStackTrace();
//            throw new JeecgBootException("openid获取失败");
        }
        return null;
    }

    @Value("${huawei.clientId}")
    public void setAppId(String clientId) {
        HwUtils.clientId = clientId;
    }

    @Value("${huawei.clientSecret}")
    public void setSecret(String clientSecret) {
        HwUtils.clientSecret = clientSecret;
    }

}
